package logic

import (
	"context"
	"encoding/json"

	"lottery-zero/internal/model"
	"lottery-zero/internal/svc"
	"lottery-zero/internal/types"

	"github.com/tal-tech/go-zero/core/logx"
)

type UserModifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserModifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) UserModifyLogic {
	return UserModifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserModifyLogic) UserModify(req types.UserModifyReq, userId string) (*types.UserInfoReply, error) {
	userInt, _ := json.Number(userId).Int64()

	userinfo := model.UserInfo{}
	l.svcCtx.PGDB.Where(&model.UserInfo{ID: uint(userInt)}).First(&userinfo)
	if req.Avatar != nil {
		userinfo.Avatar = req.Avatar
	}
	if req.DingWebHook != nil {
		userinfo.DingWebHook = req.DingWebHook
	}
	if req.Nickname != nil {
		userinfo.Nickname = req.Nickname
	}
	if req.Introduction != nil {
		userinfo.Introduction = req.Introduction
	}
	userinfo.Email = req.Email
	result := l.svcCtx.PGDB.Save(&userinfo)

	return &types.UserInfoReply{
		Id:           userinfo.ID,
		Username:     userinfo.UserAuth.Name,
		Email:        userinfo.Email,
		Nickname:     userinfo.Nickname,
		DingWebHook:  userinfo.DingWebHook,
		Avatar:       userinfo.Avatar,
		Introduction: userinfo.Introduction,
	}, result.Error
}
